///<reference path='SPRESTList.ts'/>
///<reference path='SPRESTContext.ts'/>
///<reference path='SPRESTWeb.ts'/>

// Module
module SPREST {

    // Class
    export class ListItemCollection {
        public started: bool = false;
        public ready: bool = false;
        public dfd: JQueryDeferred = $.Deferred();

        public items: SPREST.ListItem[];

        constructor (public Context: SPREST.Context, public List: SPREST.List, public QueryUrl: string) {
        }

        start(): JQueryDeferred {
            var myThis = this;

           if (myThis.started) return myThis.dfd;
            myThis.started = true;
            $.ajax(myThis.QueryUrl, {
                async: true,
                headers: { "Accept":"application/json;odata=verbose" },
                type: "GET"
            }).fail(function(req, status, error) {
                myThis.dfd.reject(myThis, req, status, error);
            }).done(function (data) { 
                myThis.items = [];
                for (var looper = 0; looper < data.d.results.length; looper++) {
                    var resultData = data.d.results[looper];
                    var li = new SPREST.ListItem(myThis.List, myThis, resultData);
                    myThis.items.push(li);
                }
                myThis.ready = true;
                myThis.dfd.resolve(myThis);
            });

            return myThis.dfd;
        }
    }

}
